package com.atsmart.app.activity;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;

import cn.jpush.android.api.JPushInterface;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.EventLogTags.Description;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 
 * @author yhl
 * TODO push通知消息
 * 2013-9-3下午4:42:18
 * {
 * 	@link Description :title:功能,内容
 *	1：通知推送，（声音提示）
 *	2：版本推送（声音提示）
 *	3：实时定位推送(不用提示)
 * }
 */
@SuppressWarnings("deprecation")
public class PushNotificationActivity extends Activity {
	private String title = "";
	private String content = "";
	private static final String TAG = PushNotificationActivity.class.getName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (null != intent) {
	        Bundle bundle = getIntent().getExtras();
	        title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
	        content = bundle.getString(JPushInterface.EXTRA_ALERT);
//	        Log.e(TAG,"标题 : " + title + "  " + "内容 : " + content);
        }
        
        if(!StringUtil.isEmptyOrNull(title)){
        	if(title.split(",")[0].equals("1")){//推送通知
	        	if(StringUtil.isEmptyOrNull(PrefsUtils.getIsNoti())){
	        		try{
						if(NavActivity.instance != null){
							NavActivity.instance.finish();
						}
					}catch (Exception e) {
					}
	        	}
				PrefsUtils.setNotifiction("1");
				Bundle bundle = new Bundle();
	        	IntentUtil.redirectToNext(PushNotificationActivity.this, NavActivity.class,bundle);
	        	finish();
        	}else if(title.split(",")[0].equals("2")){//版本推送
        		Log.e("TAG", "版本推送： ===============");
        		try {
					String url = title.split(",")[1];
					if (!StringUtil.isEmptyOrNull(url)) {
						updata(url);
					} else {
						Toast.makeText(PushNotificationActivity.this, "版本下载地址为空", Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					Toast.makeText(PushNotificationActivity.this, "版本更新异常", Toast.LENGTH_SHORT).show();
				}
        		this.finish();
        	}else{
        		Toast.makeText(PushNotificationActivity.this, "消息类型有误", Toast.LENGTH_SHORT).show();
        		this.finish();
        	}
        }
    }

	private void updata(final String url){
		new Thread() {
			public void run() {
//				Log.e(TAG, "path: = " + Environment.getExternalStorageDirectory()+ "/atsmart".toString());
				GetFileFromUrl(url, Environment.getExternalStorageDirectory()+ "/atsmart".toString());
			}

		}.start();
	}

	private static String UPDATE_SERVERAPK = "biz.apk";
	public Boolean GetFileFromUrl(String url, String path) {
		long curPosition = 0;
		long startPosition = 0;
		long endPosition = 0;
		long downloadSize = 0;

		long fileLength = 0;
		long localFileLength = 0;

		byte[] b = new byte[51200];

		long progress = 0; // 进度

		URL urlx = null;
		HttpURLConnection con = null;
		InputStream stream = null;

		File file = null;
		RandomAccessFile fos = null;

		File fPath = new File(path);
		if (!fPath.exists())
			fPath.mkdirs();

		file = new File(path, UPDATE_SERVERAPK);
//		Log.e(TAG, path + " " + UPDATE_SERVERAPK);
		try {
			fos = new RandomAccessFile(file, "rwd");
			startPosition = fos.length();

			Log.d("URL:", url);
			urlx = new URL(url);
			con = (HttpURLConnection) urlx.openConnection();
			con.setAllowUserInteraction(true);
			con.setConnectTimeout(10 * 1000);
			con.setReadTimeout(10 * 1000);
			con.setRequestMethod("GET");
			con.setRequestProperty("Referer", url);
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Range", "bytes=" + startPosition + "-");// 设置获取实体数据的范围
			con.setRequestProperty("Connection", "Keep-Alive");
			fileLength = con.getContentLength();
//			Log.e("tag", "filelenth:" + fileLength);
			if (fileLength == -1) {
//				Log.e("tag", "ERROR:" + url + "文件不存在");
				return false;
			}
			endPosition = startPosition + fileLength;

			int code = con.getResponseCode();
			if (code == 416) {
				localFileLength = file.length();
//				Log.e("tag", "size:" + localFileLength);

				if (startPosition == localFileLength) {
//					Log.e("tag", "OK");
					down();
					return true;
				}
			}
			if (code == HttpURLConnection.HTTP_OK || code == 206) {
				stream = con.getInputStream();

				localFileLength = file.length();
//				Log.e("tag", "size:" + localFileLength);
				downloadSize += startPosition;

				curPosition = startPosition;
				fos.seek(startPosition);
				int count = 0;
				while (curPosition < endPosition) {
					int len = stream.read(b, 0, 51200);

					if (len == -1){
						break;
					}
					fos.write(b, 0, len);

					curPosition = curPosition + len;

					if (curPosition > endPosition) {
						downloadSize += len - (curPosition - endPosition);
					} else {
						downloadSize += len;
					}
					count++;
					if (count > 20) {
						count = 0;
						fos.close();
						fos = new RandomAccessFile(file, "rwd");
						fos.seek(curPosition);

					}
					progress = (long) (((float) downloadSize / endPosition) * 100);
//					Log.e("tag", "progress" + progress);
					Message msg = handler.obtainMessage();
					msg.getData().putInt("step", (int) (progress));
					handler.sendMessage(msg);
				}

				stream.close();
				fos.close();
				con.disconnect();
				if (progress == 100){
					down();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			b = null;
		} finally {
			try {
				if (stream != null) {
					stream.close();
				}
			} catch (Exception e) {
				 e.printStackTrace();
			}

		}
		return true;
	}
	
	/**
	 * 下载完成，通过handler将下载对话框取消
	 */
	public void down() {
		update();
		Message message = handler.obtainMessage();
		handler.sendMessage(message);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int nStep = msg.getData().getInt("step", -1);
			if (nStep == -1) {
				// pd.dismiss();
			} else {
				showNotification(nStep);
				// pd.setProgress(nStep);
			}
		}
	};
	
	/**
	 * 安装应用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory()
						.toString() + "/atsmart", UPDATE_SERVERAPK)), "application/vnd.android.package-archive");
		startActivity(intent);

	}
	
	/**
	 * 加载消息通知服务
	 * @param s progress
	 */
	private void showNotification(int s) {
//		if (s == 100) {
//			 Log.e(TAG, "下载完成");
//		}
		NotificationManager notificationManager = (NotificationManager) this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);// 调用android系统属性
		// 显示消息通知
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, PushNotificationActivity.class), 0);
		RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.update_layout);
		contentView.setTextViewText(R.id.notificationTitle, getResources().getString(R.string.app_name));
		contentView.setTextViewText(R.id.notificationPercent, String.valueOf(s) + "%");
		contentView.setProgressBar(R.id.notificationProgress, 100, s, false);
		Notification notification = new Notification();
		notification.icon = R.drawable.icon;
		notification.tickerText = getResources().getString(R.string.app_name) + "有更新信息";
		notification.when = System.currentTimeMillis();
		notification.contentView = contentView;
		notification.contentIntent = contentIntent;
		notificationManager.notify(0, notification);

	}
}
